<template>
  <basic-container>
    <div class="dictory-wapper">
      <div class="btn-box">
        <div class="btn" v-hidden>
           <!-- <el-button @click="uploadFileOpen">上传文件</el-button> -->
           <el-button v-if="pageType==1" @click="xjWjj">新建文件夹</el-button>
        </div>
        <div class="search">
          <el-input clearable placeholder="请输入名称" v-model="searchVal" class="input-with-select">
            <el-button slot="append" icon="el-icon-search" @click="clickSearch"></el-button>
          </el-input>
        </div>
      </div>
      <div class="bread-box" v-if="breadList.length > 1">
        <div class="breadcrumb">
          <template v-for="(item,idx) in breadList">
              <div class="breadcrumb-item" v-show="idx == 0" @click="gotoBack(item,idx)">{{item.tit}}</div>
              <div class="breadcrumb-item" v-show="idx > 0 && idx < breadList.length-1"  @click="gotoBack(item,idx)"><span class="speter">>></span>{{item.tit}}</div>
              <div class="breadcrumb-item" v-show="idx == breadList.length-1"><span class="speter">>></span>{{item.tit}}</div>
          </template>
        </div>
      </div>
      <div class="list-box">
        <div class="list" v-for="(item,idx) in dataList" :key="idx">
          <div class="left">
            <div class="item">
              <img title="文件夹" @click="gotoChild(item)" v-if="item.type == 1" src="/img/filebox.png" alt="文件夹">
              <img title="资源组" @click="gotoChild(item)" v-if="item.type == 4" src="/img/filegroup.png" alt="资源组">
              <img title="资源"  @click="gotoPlay(item)" v-if="item.type == 2" src="/img/article.png" alt="资源">
            </div>
            <div class="descri-box">
              <div class="tit">
                {{item.name}}
                <span style="color:#888;font-size:12px;">
                    &nbsp;&nbsp;创建者:{{item.userName}}
                </span>
                </div>
              <div class="mark">
                <div class="des">{{item.mark || '暂无描述'}}</div>
                <div class="genxi-box">{{item.time}}</div>
              </div>
            </div>
            <div class="div_status" >
              <div style="display:flex;gap:10px">
                  <el-tag v-if="item.status==0 || item.status==3" type="danger">草稿</el-tag>
                  <el-tag v-if="item.status==2">待审核</el-tag>
                  <el-tag v-if="item.status==1" type="success">已上线</el-tag>
                  <el-tag v-if="item.status==3" type="warning">已拒绝</el-tag>
              </div>
            </div>
          </div>
          <div class="right">
            <el-button size="mini" v-hidden plain v-if="userId == item.userId && (item.type == 1 || item.type == 4) && item.status==0" @click="submitCatry(item)">提交</el-button>
            <el-button size="mini" v-hidden plain v-if="userId == item.userId && (item.type == 2) && item.status==0"  @click="submitFileStatus(item)">提交审核</el-button>
            <el-button size="mini" v-hidden plain v-if="item.type == 4 && item.status !=5"  @click="uploadFileOpen(item)">新建素材</el-button>
            <el-button size="mini" v-hidden plain v-if="item.type == 1" @click="xjSCGroup(item)">新建素材组</el-button>
            <el-button size="mini" v-hidden plain v-if="userId == item.userId && (item.type == 1 || item.type == 4)" @click="wjjCmm(item)">重命名</el-button>
            <el-button size="mini" plain type="danger" v-if="(userId == item.userId || preRow.userId == userId || userRole) && item.status !=5 && item.status !=2" @click="removeItem(item)">删除</el-button>
            <el-button size="mini" v-hidden plain  v-if="userId == item.userId &&(item.type==2 || item.type==3) && item.status !=5 && item.status !=2"   @click="editForm(item)">编辑</el-button>
            <el-button size="mini" plain  v-if="item.type==2 || item.type==3"   @click="gotoPlay(item)">查看详情</el-button>
          </div>
        </div>
        <el-empty v-if="dataList.length==0" :image-size="100"></el-empty>
      </div>
      <div class="pagination-box">
        <el-pagination
            background
            hide-on-single-page
            layout="prev, pager, next, total"
            :total="total"
            :page-size="size"
            :current-page="page"
            @current-change="currentChange"
        >
          </el-pagination>
      </div>
    </div>
    <!-- 新建修改文件夹 -->
    <el-dialog
      :title="editStatus==1?'新建文件夹':'文件夹重命名'"
      :visible.sync="cagOpenFlagh"
      :modal-append-to-body="false"
      width="30%"
      :before-close="handleClose">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="文件夹名称" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入文件夹名称"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="mark">
          <el-input v-model="ruleForm.mark" placeholder="请输入描述"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cagOpenFlagh = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 新建素材包 -->
    <el-dialog
      :title="editStatus==1?'新建素材包':'修改素材包'"
      :visible.sync="scbOpenFlagh"
      :modal-append-to-body="false"
      width="30%">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="素材包名称" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入素材包名称"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="mark">
          <el-input v-model="ruleForm.mark" placeholder="请输入描述"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="scbOpenFlagh = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm',4)">确 定</el-button>
      </span>
    </el-dialog>
     <!-- 上传文件 -->
    <el-dialog
      :title="uploadStatus==1?'新建素材':'修改素材'"
      :visible.sync="uploadOpenFlagh"
      :modal-append-to-body="false"
      width="50%"
      :before-close="uploadHandleClose"
    >
      <el-form :model="uplodRuleForm" :rules="uploadRules" ref="uplodRuleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="文件名称" prop="name">
          <el-input v-model="uplodRuleForm.name" placeholder="请输入文件名称"></el-input>
        </el-form-item>
        <el-form-item label="编写素材" prop="artContent">
          <vue-wangeditor :htmlValue="uplodRuleForm.artContent" @resetHtml="resetHtml" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="uploadOpenFlagh = false">取 消</el-button>
        <el-button type="primary" @click="uploadSubmit('uplodRuleForm')" :loading="configLoading">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 资源播放 -->
    <el-dialog
      title="资源预览"
      :visible.sync="playFlag"
      :modal-append-to-body="false"
      width="1000px"
      top="30px"
    >

      <div v-if="playFlag" v-html="videoObj.artContent"></div>
    </el-dialog>
  </basic-container>
</template>
<script>
  import {
   getList,add,remove,updateNameById,addSubCatory,addSubFiles,aduitById
  } from "@/api/resource/depart";
  import {removeFile,signFile} from '@/api/common'
  import {mapGetters} from "vuex";
  import vueWangeditor from '@/components/wangEditor/index.vue'
  export default {
    data() {
      return {
        dataList:[],
        page:1,
        size:8,
        total:0,
        searchVal:'',
        pid:0,
        groupPid:0,
        breadList:[{tit:'根目录',pid:0}],
        configLoading:false,
        // 文件夹开关
        cagOpenFlagh:false,
        editStatus:1,
        currentRow:{},
        ruleForm: {
          name: '',
          mark:''
        },
        rules: {
          name: [
            { required: true, message: '请输入文件夹名称', trigger: 'blur' },
            { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
          ],
          mark: [
            { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
          ]
        },
        // 上传文件相关
        uploadStatus:1,
        uploadOpenFlagh:false,
        uplodRuleForm: {
          name: '',
          artContent:''
        },
        uploadRules: {
          name: [
            { required: true, message: '请输入文件名称', trigger: 'blur' },
            { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
          ],
           artContent: [
            { required: true, message: '请编写文章', trigger: 'blur' }
          ]
        },
        // 资源预览相关
        playFlag:false,
        videoObj:{},
        // 素材包
        scbOpenFlagh:false,
        // 素材pid
        sczyBId:0,
        pageType:1,
        // 当前文件
        currentRow:null,
        //上级的文件
        preRow:{
          userId:null
        }
      };
    },
    computed: {
      ...mapGetters(["userInfo"]),
      userId() {
        return this.userInfo.user_id;
      },
      userRole(){
        return this.userInfo.is_admin > 0?true:false;
      }
    },
    components:{
      vueWangeditor
    },
    mounted(){
      this.getListData()
    },
    methods: {
      // 申请重做
      applyRedo(item){
        this.currentRow = item
         this.$confirm('确定要申请重做吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.redo(this.currentRow)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消编辑'
          });          
        })
      },
      async redo(row){
         await aduitById(row.id,4)
         this.getListData()
      },
      // 提交文件
      async submitFileStatus(item){
       this.currentRow = item
       this.$confirm('确定要提交审核吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.realFiles(this.currentRow)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消编辑'
          });          
        })
      },
      async realFiles(row){
        await addSubFiles({pid:row.pid,id:row.id})
        this.getListData()
      },
      // 提交文件夹，文件组
      async submitCatry(item){
       this.currentRow = item
       this.$confirm('确定要提交吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.realCatry(this.currentRow)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消编辑'
          });          
        })
      },
      async realCatry(row){
        await addSubCatory({pid:row.pid,id:row.id})
        this.getListData()
      },
      editForm(item){
         this.$confirm('此操作将会重新审核该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.uploadStatus=2;
          this.uploadOpenFlagh = true
          this.uplodRuleForm = {id:item.id,name:item.name,artContent:item.artContent}
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消编辑'
          });          
        });
      },
      resetHtml(str){
        this.$set(this.uplodRuleForm,'artContent',str)
      },
     onCopy(){
        this.$message.success('复制链接成功！')
     },
     gotoPlay(item){
        this.playFlag = true;
        this.videoObj = item;
     },
     async getListData(){
       const res = await getList(this.page,this.size,{searchVal:this.searchVal,pid:this.pid});
       this.dataList = res.data.data.list
       this.total = res.data.data.total
       this.page = res.data.data.page
     },
     currentChange(page){
        this.page = page
        this.getListData()
     },
     clickSearch(){
       this.getListData()
     },
     xjWjj(){
        this.cagOpenFlagh=true;
        this.editStatus=1;
        this.$set(this.ruleForm, 'name', '')
        this.$set(this.ruleForm, 'mark', '')
     },
     xjSCGroup(item){
        this.groupPid = item.id
        this.scbOpenFlagh=true;
        this.editStatus=1;
        this.$set(this.ruleForm, 'name', '')
        this.$set(this.ruleForm, 'mark', '')
     },
     gotoChild(item){
       this.preRow = item
       this.pageType = item.type
       this.page = 1
       this.dataList = []
       this.breadList.push({tit:item.name,pid:item.id,type:item.type})
       this.pid = item.id
       this.getListData()
     },
     gotoBack(item,idx){
       if(idx == 0){
         this.breadList = [{tit:'根目录',pid:0}]
         this.pageType =1
       }else{
           const newArr = this.breadList.slice(0,idx+1)
           this.breadList = newArr
           if(item.type){
             this.pageType =item.type
           }
       }
       this.pid = item.pid
       this.getListData()
     },
     handleClose(){
       this.$refs['ruleForm'].resetFields();
       this.cagOpenFlagh = false
       this.scbOpenFlagh=false;
     },
     async submitCagtory(type){
       if(this.editStatus ==1){
          const obj = {...this.ruleForm,artContent:'',pid:type==4?this.groupPid:this.pid,type}
          const res = await add(obj)
          if(res.data.code==200){
            this.getListData()
            this.handleClose()
          }
       }else{
          const obj = {...this.ruleForm,id:this.currentRow.id,pid:this.pid}
          const res = await updateNameById(obj)
          if(res.data.code==200){
            this.getListData()
            this.handleClose()
          }
       }

     },
     submitForm(formName,type=1) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.submitCagtory(type)
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      async removeItem(item){
        this.$confirm('确定要删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then( async() => {
            const res = await remove(item.id)
            if(res.data.code==200){
            this.getListData()
            }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消编辑'
          });          
        });
       
      },
      wjjCmm(item){
        this.cagOpenFlagh = true
        this.editStatus=2;
        this.currentRow = item;
        this.$set(this.ruleForm, 'name', item.name)
        this.$set(this.ruleForm, 'mark', item.mark)
      },
      // 上传文件相关
      uploadFileOpen(item){
          this.sczyBId = item.id
          this.$set(this.uplodRuleForm, 'name', '')
          this.$set(this.uplodRuleForm, 'artContent', '')
          this.$set(this.uplodRuleForm, 'fileName', '')
          this.uploadOpenFlagh=true;
          this.uploadStatus=1;
      },
      uploadHandleClose(){
        this.uploadOpenFlagh = false
      },
      beforeImport(file){
        if (!file || !file.name || !file.type || !file.size) {
          this.$message({
            type: 'warning',
            message: '不支持上传空文件!',
          })
          return false
        }
        if (!file.name.endsWith('.png') && !file.name.endsWith('.jpg') && !file.name.endsWith('.mp4')) {
          this.$message({
            type: 'warning',
            message: '不支持上传当前文件类型!',
          })
          return false
        }
        return true
      },
      async uploadSectionFile(data)  {
        this.configLoading = true;
        const file = data.file;
        const ossurl = 'https://s.xazyzx.com/'
        const res = await signFile({name:file.name})
        const signData = res.data.data
         // ⽂件对象
        const formData = new FormData()
        if(res.data.code == 200){
            formData.append("signature", signData.signature);
            formData.append("name", signData.filename);
            formData.append("policy", signData.policy);
            formData.append("OSSAccessKeyId", signData.ossAccessKeyId);
            formData.append("success_action_status", "200");
            formData.append("key", signData.dir +'/'+ signData.filename);
            formData.append('file', file)
            fetch(signData.host, {
              method: "POST",
              body: formData,
            }).then((response) => {
              this.configLoading = false;
              if (!response.ok) {
                throw new Error("文件上传到OSS失败");
              }else{
                  this.$set(this.uplodRuleForm,'url',ossurl + signData.dir +'/'+ signData.filename)
                  this.$set(this.uplodRuleForm, 'fileName', signData.dir +'/'+ signData.filename)
              }
            });
        }else{
          this.$refs.upload.clearFiles()
          this.$message({
            type: 'warning',
            message: '服务端签名失败',
          })
        }
      },
      uploadSubmit(formName){
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.submitFile()
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      async submitFile(){
        const obj = {...this.uplodRuleForm,pid:this.sczyBId,type: 2}
        const res = await add(obj)
        if(res.data.code==200){
          this.getListData()
          this.uploadHandleClose()
          this.$refs.upload.clearFiles()
        }
     },
      async onRemove(){
        await removeFile({name:this.uplodRuleForm.fileName})
        this.$set(this.uplodRuleForm,'url','')
        this.$set(this.uplodRuleForm, 'fileName','')
     }
    }
  };
</script>

<style lang='scss' scoped>
.div_status{
  display: flex;
  height: 100%;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.video-icon{
  position: absolute;
  left: 0;
  top: 0;
}
.bread-box{
  .speter{
    margin: 0 6px;
  }
  .breadcrumb{
    display: flex;
    align-items: flex-end;
    .breadcrumb-item{
      font-size: 14px;
      color: #bfbfbf;
      cursor: pointer;
      user-select: none;
      &:last-child{
        cursor: default;
        color: #333;
      }
    }
  }
}
.dictory-wapper{
  display: flex;
  flex-direction: column;
  min-height: 200px;
  .btn-box{
    padding-bottom: 18px;
    display: flex;
    justify-content: space-between;
    .search{
      width: 40%;
    }
  }
  .list-box{
    overflow-x: hidden;
    overflow-y: auto;
    border: 1px solid #ddd;
    height: auto;
    .list{
      display: flex;
      padding: 10px 20px 10px 20px;
      border-bottom: 1px solid #ddd;
      border-top: none;
      cursor: pointer;
      user-select: none;
      justify-content: space-between;
      .left{
        display: flex;
      }
      .right{
        height: 100%;
        display: flex;
        align-items: center;
        margin-top: 10px;
      }
      &:last-child{
          border-bottom: none;
      }
      .item{
        margin-right: 20px;
        img{
          width: 50px;
          margin-top: 10px;
        }
      }
      .descri-box{
        .tit{
          font-size: 16px;
          color: #333;
          padding-top: 10px;
          margin-bottom: 10px;
        }
        .mark{
          display: flex;
          align-items: flex-end;
          .des{
              font-size: 14px;
              margin-right: 16px;
              color: #bfbfbf;
          }
          .genxi-box{
              font-size: 14px;
              margin-right: 16px;
              color: #bfbfbf;
          }
        }
      }
    }
  }
  .pagination-box{
    width: 100%;
    display: flex;
    justify-content: center;
    margin-top: 18px;
  }
  .bread-box{
    margin-bottom: 18px;
  }
}
</style>
